<template>
  <div class="watermark-container">
    <!-- 返回首页按钮 -->
    <div class="back-button-container">
      <router-link to="/" class="back-button">
        <el-icon><ArrowLeft /></el-icon>
        🏠点击返回主页面
      </router-link>
    </div>

    <!-- 主内容区域 -->
    <div class="content-wrapper">
      <div class="header">
        <h1 class="page-title">智能去水印工具</h1>
        <p class="subtitle">支持图片和视频的智能水印去除</p>
      </div>

      <!-- 功能切换按钮 -->
      <div class="mode-switch">
        <button 
          class="mode-btn" 
          :class="{ active: activeMode === 'image' }"
          @click="switchMode('image')"
        >
          <el-icon><Picture /></el-icon>
          🧩图片去水印
        </button>
        <button 
          class="mode-btn" 
          :class="{ active: activeMode === 'video' }"
          @click="switchMode('video')"
        >
          <el-icon><VideoPlay /></el-icon>
          🎞️视频去水印
        </button>
      </div>

      <!-- 上传区域 -->
      <div class="upload-section">
        <!-- 图片上传 -->
        <div v-if="activeMode === 'image'" class="upload-area">
          <el-upload
            class="upload-dragger"
            drag
            :action="'#'"
            :auto-upload="false"
            :show-file-list="false"
            :accept="'image/*'"
            @change="handleImageUpload"
          >
            <el-icon class="upload-icon"><Plus /></el-icon>
            <div class="upload-text">
              <p>拖拽图片到此处或 <em>📁点击选择</em></p>
              <p class="upload-tip">支持 JPG、PNG、BMP 格式</p>
            </div>
          </el-upload>
          
          <!-- 图片预览 -->
          <div v-if="imagePreview" class="preview-container">
            <img :src="imagePreview" alt="预览" class="preview-image" />
            <div class="file-info">
              <p>文件名: {{ selectedFile?.name }}</p>
              <p>大小: {{ formatFileSize(selectedFile?.size) }}</p>
            </div>
          </div>
        </div>

        <!-- 视频上传 -->
        <div v-if="activeMode === 'video'" class="upload-area">
          <el-upload
            class="upload-dragger"
            drag
            :action="'#'"
            :auto-upload="false"
            :show-file-list="false"
            :accept="'video/*'"
            @change="handleVideoUpload"
          >
            <el-icon class="upload-icon"><Plus /></el-icon>
            <div class="upload-text">
              <p>拖拽视频到此处或 <em>点击选择</em></p>
              <p class="upload-tip">支持 MP4、AVI、MOV、MKV 格式</p>
            </div>
          </el-upload>
          
          <!-- 视频预览 -->
          <div v-if="videoPreview" class="preview-container">
            <video :src="videoPreview" controls class="preview-video"></video>
            <div class="file-info">
              <p>文件名: {{ selectedFile?.name }}</p>
              <p>大小: {{ formatFileSize(selectedFile?.size) }}</p>
            </div>
          </div>
        </div>
      </div>

      <!-- 水印区域选择 -->
      <div v-if="selectedFile" class="options-section">
        <h3>水印区域设置</h3>
        <div class="options-grid">
          <div class="option-item">
            <label>处理方式:</label>
            <el-select v-model="processMethod" placeholder="请选择处理方式">
              <el-option label="自动检测水印区域" value="auto" />
              <el-option label="手动指定水印区域" value="manual" />
            </el-select>
          </div>
          
          <div v-if="processMethod === 'manual'" class="option-item">
            <label>水印区域坐标:</label>
            <div class="coordinates-input">
              <el-input v-model="maskCoords[0]" placeholder="左上角 x,y" />
              <el-input v-model="maskCoords[1]" placeholder="右下角 x,y" />
            </div>
            <p class="tip">格式: x,y (例如: 100,50)</p>
          </div>
        </div>
      </div>

      <!-- 处理按钮 -->
      <div v-if="selectedFile" class="action-section">
        <el-button 
          type="primary" 
          size="large" 
          :loading="processing"
          :disabled="!canProcess"
          @click="processWatermark"
        >
          {{ processing ? '处理中...' : '开始去水印' }}
        </el-button>
      </div>

      <!-- 结果展示 -->
      <div v-if="resultUrl" class="result-section">
        <h3>处理结果</h3>
        <div class="result-container">
          <img v-if="activeMode === 'image'" :src="resultUrl" alt="处理结果" class="result-image" />
          <video v-if="activeMode === 'video'" :src="resultUrl" controls class="result-video"></video>
          
          <div class="result-actions">
            <el-button type="success" @click="downloadResult">
              <el-icon><Download /></el-icon>
              下载结果
            </el-button>
            <el-button @click="resetForm">重新处理</el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

// 状态管理
const activeMode = ref('image')
const selectedFile = ref(null)
const imagePreview = ref('')
const videoPreview = ref('')
const processing = ref(false)
const resultUrl = ref('')
const processMethod = ref('auto')
const maskCoords = ref(['', ''])

// 计算属性
const canProcess = computed(() => {
  if (processMethod.value === 'manual') {
    return maskCoords.value[0] && maskCoords.value[1]
  }
  return true
})

// 方法
const switchMode = (mode) => {
  activeMode.value = mode
  resetForm()
}

const handleImageUpload = (file) => {
  selectedFile.value = file.raw
  imagePreview.value = URL.createObjectURL(file.raw)
  videoPreview.value = ''
  resultUrl.value = ''
}

const handleVideoUpload = (file) => {
  selectedFile.value = file.raw
  videoPreview.value = URL.createObjectURL(file.raw)
  imagePreview.value = ''
  resultUrl.value = ''
}

const formatFileSize = (bytes) => {
  if (!bytes) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const parseCoordinates = (coordStr) => {
  if (!coordStr) return null
  const [x, y] = coordStr.split(',').map(Number)
  return [x, y]
}

const processWatermark = async () => {
  if (!selectedFile.value) return
  
  processing.value = true
  
  try {
    const formData = new FormData()
    formData.append(activeMode.value, selectedFile.value)
    
    let apiEndpoint = ''
    let requestData = {}
    
    if (activeMode.value === 'image') {
      apiEndpoint = '/api/watermark/remove-image'
      
      if (processMethod.value === 'manual') {
        const coords = [
          parseCoordinates(maskCoords.value[0]),
          parseCoordinates(maskCoords.value[1])
        ]
        if (coords[0] && coords[1]) {
          formData.append('mask_coords', JSON.stringify(coords))
        }
      } else {
        // 自动检测模式
        const reader = new FileReader()
        reader.readAsDataURL(selectedFile.value)
        const base64Image = await new Promise((resolve) => {
          reader.onload = () => resolve(reader.result)
        })
        
        const detectResponse = await axios.post('/api/watermark/detect-regions', {
          image: base64Image
        })
        
        if (detectResponse.data.regions && detectResponse.data.regions.length > 0) {
          formData.append('mask_coords', JSON.stringify(detectResponse.data.regions[0]))
        }
      }
      
    } else if (activeMode.value === 'video') {
      apiEndpoint = '/api/watermark/remove-video'
      
      if (processMethod.value === 'manual') {
        const coords = [
          parseCoordinates(maskCoords.value[0]),
          parseCoordinates(maskCoords.value[1])
        ]
        if (coords[0] && coords[1]) {
          formData.append('mask_coords', JSON.stringify(coords))
        }
      }
    }
    
    const response = await axios.post(apiEndpoint, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      responseType: 'blob'
    })
    
    const blob = new Blob([response.data], { 
      type: activeMode.value === 'image' ? 'image/jpeg' : 'video/mp4' 
    })
    resultUrl.value = URL.createObjectURL(blob)
    
    ElMessage.success('去水印完成！')
    
  } catch (error) {
    console.error('处理失败:', error)
    ElMessage.error('处理失败，请重试')
  } finally {
    processing.value = false
  }
}

const downloadResult = () => {
  if (!resultUrl.value) return
  
  const link = document.createElement('a')
  link.href = resultUrl.value
  link.download = `processed_${selectedFile.value.name}`
  link.click()
}

const resetForm = () => {
  selectedFile.value = null
  imagePreview.value = ''
  videoPreview.value = ''
  resultUrl.value = ''
  processMethod.value = 'auto'
  maskCoords.value = ['', '']
}
</script>

<style scoped>
@import '../assets/RemoveWatermark.css'
</style>
